import { Directive, forwardRef } from '@angular/core';
import { AbstractControl, NG_VALIDATORS, Validator } from '@angular/forms';

@Directive({
  selector: '[appMoreThanZero]',
  providers: [{
    provide: NG_VALIDATORS,
    useExisting: forwardRef(() => MoreThanZeroDirective),
    multi: true
  }]
})
/**
 * 自定义验证器，用于验证值是否大于0：大于0验证通过返回null，否则返回{moreThanZero: true}错误对象
 */
export class MoreThanZeroDirective implements Validator {

  constructor() {}

  validate(control: AbstractControl): {[key: string]: any} {
    const value = control.value || 0;
    if (value > 0) {
      return null;
    }
    return {moreThanZero: true};
  }
}
